package com.ttdj.cmel.service;

import android.app.DownloadManager;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.ttdj.cmel.CMELApplication;
import com.ttdj.cmel.bean.CMELUpgradeBean;
import com.ttdj.cmel.retrofit.UpgradeService;
import com.ttdj.cmel.utils.HmSharedPreferencesUtils;
import com.ttdj.cmel.utils.PackageInstallObserver;
import com.ttdj.cmel.utils.Utils;

import java.io.File;
import java.lang.reflect.Method;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by gaopeng on 2018/7/11.
 */

public class CMELUpdataIntentService extends IntentService {
    private String mApkPath;
    private String mDownloadUrl;
    private boolean isUpdating;
    private long mApkId;
    private static final String TAG = "UserCenterUpdata";

    public CMELUpdataIntentService() {
        super("usercenter_updata_service");
    }

    /**
     * @param context
     * @param type    1 检测是否有新版本  2 更新apk
     */
    public static void startService(Context context, int type) {
        Intent intent = new Intent(context, CMELUpdataIntentService.class);
        intent.putExtra("pull_apk_type", type);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        int type = intent.getIntExtra("pull_apk_type", 1);
        if (type == 1) {
            sendAPKVersion();
        } else if (type == 2) {

            if (mApkPath == null || mApkPath.isEmpty()) {
                mApkPath = (String) HmSharedPreferencesUtils.getParam("apkPath", "");
            }
            Uri contentUri = Uri.fromFile(new File(mApkPath));
            installQuiet(contentUri);

        }
    }

    private void sendAPKVersion() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://o.heimilink.com/").addConverterFactory(GsonConverterFactory.create()).build();
        UpgradeService service = retrofit.create(UpgradeService.class);
        Call<CMELUpgradeBean> call = service.upgradeAPK("TTDJ", "shark", Utils.getPhoneImei(), Utils.getAppVersion());
        call.enqueue(new Callback<CMELUpgradeBean>() {
            @Override
            public void onResponse(Call<CMELUpgradeBean> call, Response<CMELUpgradeBean> response) {
                Log.d(TAG, "==new_version_response_content== " + response.message());
                if (response != null && response.body() != null) {
                    if (response.body().getData().getUrl() != null && !response.body().getData().getUrl().isEmpty()) {
                        mDownloadUrl = response.body().getData().getUrl();
                        download();
                    }

                } else {
                    Log.d(TAG, "response is null.");
                }
            }

            @Override
            public void onFailure(Call<CMELUpgradeBean> call, Throwable t) {
                Log.e(CMELApplication.TAG, "升级接口异常：：" + t.getMessage());
            }
        });
    }

    private void download() {
        if (TextUtils.isEmpty(mDownloadUrl)) {
            return;
        }

        String filePath = CMELApplication.getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

        mApkPath = filePath + File.separator + "update.apk";
        File file = new File(mApkPath);
        if (file.exists()) {
            Log.e(CMELApplication.TAG, "usercenter apk文件存在，删除");
            file.delete();
        }
        Uri fileUri = Uri.parse("file://" + mApkPath);
        Uri uri = Uri.parse(mDownloadUrl);
        DownloadManager downloadManager = (DownloadManager) CMELApplication.getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setVisibleInDownloadsUi(true);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        request.setDestinationUri(fileUri);
        Long mApkId = downloadManager.enqueue(request);
        isUpdating = true;
        HmSharedPreferencesUtils.setParam("showboomApkID", mApkId);
        HmSharedPreferencesUtils.setParam("apkPath", mApkPath);
    }

    /**
     * 实现静默安装的代码
     */
    public void installQuiet(Uri fileUri) {

        PackageManager pm = CMELApplication.getApplication().getPackageManager();
        Class<?>[] types = new Class[]{Uri.class, IPackageInstallObserver.class, int.class, String.class};
        try {
            Method method = pm.getClass().getMethod("installPackage", types);
            method.invoke(pm, fileUri, new PackageInstallObserver(), Utils.INSTALL_REPLACE_EXISTING, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
